﻿@using BlazorWebAssemblyDemo.Authentication
@using Microsoft.AspNetCore.Components.Authorization
@using SharedClassLibrary.Contracts
@using SharedClassLibrary.DTOs

@page "/login"
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
@inject IUserService UserService;
@inject IJSRuntime JS
<div class="container">
    <div class="row">
        <div class="col-md-6">
            <EditForm Enhance Model="User" OnValidSubmit="HandleLogin">
                <DataAnnotationsValidator />
                <ValidationSummary />

                <div class="card-header">登录</div>
                <div class="card-body">
                    <div class="mb-3">
                        <input @bind="User.UserName" class="form-control" placeholder="账号" />
                    </div>

                    <div class="mb-3">
                        <input @bind="User.Password" type="password" class="form-control" placeholder="密码" />
                    </div>

                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary float-end">登录</button>
                </div>
            </EditForm>
        </div>
    </div>
</div>
@code {
    public LoginDTO User { get; set; } = new LoginDTO();

    async Task HandleLogin()
    {
        var response = await UserService.LoginAsync(User);
        if (response?.Flag == true)
        {
            await JS.InvokeVoidAsync("alert", "登录成功");
            var customAuthenticationStateProvider = AuthenticationStateProvider as JwtAuthenticationStateProvider;
            await customAuthenticationStateProvider!.NotifyUserAuthentication(response.Token);
            await Task.Delay(1);//此代码不能去掉：否则：在登录时，登录成功了，但页面会还停留在登录页，用户以为登录失败
            NavigationManager.NavigateTo("/");
        }
        else
        {
            await JS.InvokeVoidAsync("alert", "登录失败");
        }
    }
}